﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views
{
    /// <summary>
    /// 详情页有两个接口
    /// <para>漫画基本信息</para>
    /// <para>漫画资源站</para>
    /// </summary>
    public partial class ComicDetailPage : PhoneApplicationPage
    {
        private string comicId = string.Empty;
        public ComicDetailPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            //
            BindApplication();

            if (!base.NavigationContext.QueryString.ContainsKey("comicId"))
            {
                base.NavigationService.GoBack();
                return;
            }
            comicId = base.NavigationContext.QueryString["comicId"];
            if (string.IsNullOrWhiteSpace(comicId))
            {
                base.NavigationService.GoBack();
                return;
            }

            testdetail(comicId);
            testcomicsource(comicId);
        }

        void BindApplication()
        {
            //如果是新书则显示appBarNew，如果书架已经有了就显示appBarLocalCache
            ApplicationBar = (ApplicationBar)Resources["appBarNew"];
        }


        public void testdetail(string comicId)
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/comicsdetail_v2?bigbookid=", comicId.ToString());


            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"info\":{}") >= 0)
                        {
                            LogHelper.LogError("未找到对应漫画！", this.GetType(), MethodBase.GetCurrentMethod());
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicDetailBase>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Comicsdetail != null && rootCharacterString.Info.Comicsdetail.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var detailInfo = rootCharacterString.Info.Comicsdetail;
                            BindComicDetail(detailInfo);
                        }

                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {

                }
            }, webTask);
        }

        void BindComicDetail(ObservableCollection<JsonComicDetailComicsdetail> items)
        {
            JsonComicDetailComicsdetail item = (from p in items select p).FirstOrDefault<JsonComicDetailComicsdetail>();
            if (item == null)
                return;

            this.txtTitle.Text = item.BigbookName;
            this.gridComicDetailBase.DataContext = item;


        }


        #region 漫画源站点

        public void testcomicsource(string comicId)
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/bigbooksource_v3?bigbookid=", comicId.ToString());


            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        if (result.IndexOf("\"comicssource\":{}") >= 0)
                        {
                            //无数据
                            return;
                        }
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicsDetailSource>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Comicssource != null && rootCharacterString.Info.Comicssource.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            var detailInfo = rootCharacterString.Info.Comicssource;
                            BindComicDetailSource(detailInfo);
                        }
                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {

                }
            }, webTask);
        }

        void BindComicDetailSource(ObservableCollection<Comicssource> items)
        {
            if (items != null && items.Count > 0)
            {
                this.llsComicSource.ItemsSource = items;
            }
        }

        #endregion 漫画源站点


        /// <summary>
        /// 作者的漫画列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtAuthor_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            string searchKeyword = this.txtAuthor.Text.ToString();
            if (!string.IsNullOrWhiteSpace(searchKeyword))
            {
                NaviService.Navigate(ComicIslandPage.SearchBookAuthorPage, string.Concat("?searchKeyword=", Uri.EscapeDataString(searchKeyword), "&searchType=", ((int)KEYS.SearchType.Detail).ToString()));
            }
        }


        private void appBarAddFavs_Click(object sender, EventArgs e)
        {
            //TODO 收藏则添加至书架
        }

        private void appBarStartReader_Click(object sender, EventArgs e)
        {
            //开始阅读，导航至章节页面
            if (string.IsNullOrWhiteSpace(comicId))
                return;

//            NaviService.Navigate(ComicIslandPage.ComicChapterPage, string.Concat("?comicId=", comicId));
        }

        private void appBarCancelFavs_Click(object sender, EventArgs e)
        {

        }

        private void appBarGoOnReader_Click(object sender, EventArgs e)
        {

        }


    }
}